import { createRouter, createWebHashHistory, createWebHistory } from "vue-router"
import { staticRouter, errorRouter } from "./modules/staticRouter"
import { useAuthStore } from "@/store/modules/auth"
import { initDynamicRouter } from "./modules/dynamicRouter"
import { HOME_URL, LOGIN_URL } from "@/config"

import NProgress from "@/config/nprogress"

const mode = import.meta.env.VITE_ROUTER_MODE
const routerMode = {
    hash: () => createWebHashHistory(),
    history: () => createWebHistory()
}
/**
 * @description 📚 路由参数配置简介
 * @param path ==> 路由菜单访问路径
 * @param name ==> 路由 name (对应页面组件 name, 可用作 KeepAlive 缓存标识 && 按钮权限筛选)
 * @param redirect ==> 路由重定向地址
 * @param component ==> 视图文件路径
 * @param meta ==> 路由菜单元信息
 * @param meta.icon ==> 菜单和面包屑对应的图标
 * @param meta.title ==> 路由标题 (用作 document.title || 菜单的名称)
 * @param meta.activeMenu ==> 当前路由为详情页时，需要高亮的菜单
 * @param meta.isLink ==> 路由外链时填写的访问地址
 * @param meta.isHide ==> 是否在菜单中隐藏 (通常列表详情页需要隐藏)
 * @param meta.isFull ==> 菜单是否全屏 (示例：数据大屏页面)
 * @param meta.isAffix ==> 菜单是否固定在标签页中 (首页通常是固定项)
 * @param meta.isKeepAlive ==> 当前路由是否缓存
 * */

const router = createRouter({
    history: routerMode[mode](),
    routes: [...staticRouter, ...errorRouter],
    strict: false,
    scrollBehavior: () => ({ left: 0, top: 0 })
})

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
    const authStore = useAuthStore()
    NProgress.start()
    // 2.动态设置标题
    const title = import.meta.env.VITE_GLOB_APP_TITLE
    document.title = to.meta.title ? `${to.meta.title} - ${title}` : title

    if (!authStore.getMenuListState.length) {
        await initDynamicRouter()
        const allRoutes = router.getRoutes()
        // console.log(allRoutes)
        // const layoutRoutes = allRoutes.filter(route =>
        //     route.name === 'layout'
        // )[0]?.children
        // console.log("123===>", layoutRoutes)
        return next({ ...to, replace: true })
    }

    next()
})

/**
 * @description 路由拦截 afterEach
 * */
router.afterEach((to, from) => {
    // console.log("路由跳转完成")
    NProgress.done()
})

export default router
